<template>
  <n-card title="">
    <template #header>
      <div style="display: flex; align-items: center">
        <span>发布闲书（加入了自定义语法，最终效果以预览为准）</span>
        <n-popover placement="bottom" trigger="click">
          <template #trigger>
            <n-icon size="20" style="cursor: help"
              ><HelpCircleOutline
            /></n-icon>
          </template>
          <mySyntaxDialog></mySyntaxDialog>
        </n-popover>
      </div>
    </template>
    <div
      style="
        margin-bottom: 1em;
        text-align: right;
        display: flex;
        gap: 10px;
        justify-content: flex-end;
      "
    >
      <div>
        <n-button type="primary" dashed size="small" @click="btnView">
          <template #icon>
            <n-icon>
              <EyeOutline />
            </n-icon>
          </template>
          预览
        </n-button>
      </div>
      <div>
        <n-button
          type="primary"
          dashed
          size="small"
          @click="handleValidateClick"
        >
          <template #icon>
            <n-icon>
              <PaperPlaneOutline />
            </n-icon>
          </template>
          发送
        </n-button>
      </div>
    </div>
    <div>
      <n-form
        label-placement="left"
        ref="formRef"
        :label-width="80"
        :model="formValue"
        :rules="rules"
        size="medium"
        inline
        style="flex-direction: column"
      >
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="标题" path="title">
            <n-input v-model:value="formValue.title" placeholder="请输入标题" />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="心情">
            <n-input v-model:value="formValue.mood" placeholder="请输入心情" />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="图标">
            <n-popover trigger="hover" placement="bottom">
              <template #trigger>
                <div class="moods" style="width: auto">
                  <n-button class="icon-btn">
                    <template #icon>
                      <n-icon><img :src="moodIcon" alt="" srcset="" /></n-icon>
                    </template>
                  </n-button>
                </div>
              </template>
              <div class="moods">
                <template v-for="item in moodSvgIcons">
                  <n-button
                    circle
                    class="icon-btn"
                    @click="iconBtn(item.name, 1)"
                  >
                    <template #icon>
                      <n-icon><img :src="item.name" alt="" srcset="" /></n-icon>
                    </template>
                  </n-button>
                  <!-- <img :src="item.name" alt="" srcset="" /> -->
                </template>
              </div>
            </n-popover>
          </n-form-item-gi>
        </n-grid>

        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="6" label="天气">
            <n-input
              v-model:value="formValue.weather"
              placeholder="请输入天气"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="图标">
            <n-popover trigger="hover" placement="bottom">
              <template #trigger>
                <div class="moods" style="width: auto">
                  <n-button class="icon-btn">
                    <template #icon>
                      <n-icon
                        ><img :src="weatherIcon" alt="" srcset=""
                      /></n-icon>
                    </template>
                  </n-button>
                </div>
              </template>
              <n-scrollbar style="max-height: 220px">
                <div class="moods">
                  <template v-for="item in weatherSvgIcons">
                    <n-button
                      circle
                      class="icon-btn"
                      @click="iconBtn(item.name, 2)"
                    >
                      <template #icon>
                        <n-icon
                          ><img :src="item.name" alt="" srcset=""
                        /></n-icon>
                      </template>
                    </n-button>
                    <!-- <img :src="item.name" alt="" srcset="" /> -->
                  </template>
                </div>
              </n-scrollbar>
            </n-popover>
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="是否私密">
            <n-switch v-model:value="formValue.isPrivacy" />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="访问密码">
            <n-input
              v-model:value="formValue.password"
              placeholder="私密文章访问密码"
              :disabled="!formValue.isPrivacy"
            />
          </n-form-item-gi>
        </n-grid>

        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="6" label="是否红旗">
            <n-switch v-model:value="formValue.isRedFlag" />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="是否评论">
            <n-switch v-model:value="formValue.isComments" />
          </n-form-item-gi>
          <n-form-item-gi :span="6" label="是否可用">
            <n-switch v-model:value="formValue.enable" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </div>
    <MdEditor
      type="linkAttr"
      target="_blank"
      v-model="formValue.content"
      previewTheme="github"
      codeTheme="gradient"
      style="min-height: 80vh"
      @onUploadImg="onUploadImg"
    />
    <my-dialog
      @closeModal="closeModal"
      :showModal="showModal"
      ref="myDialogRef"
    ></my-dialog>
  </n-card>
</template>

<script setup lang="ts">
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import { h, onMounted, ref } from "vue";
import {
  PaperPlaneOutline,
  EyeOutline,
  HelpCircleOutline,
} from "@vicons/ionicons5";
import myDialog from "@/components/contentView.vue";
import mySyntaxDialog from "@/components/syntaxDialog.vue";
import { createNotesInfoRequest } from "@/models/notesModel.ts";
import { createNotes, getNotesById, updateNotes } from "@/api/notes";
import { uploadImageFile } from "@/api/file.ts";
import { useRoute, useRouter } from "vue-router";

// 在你的组件中或单独的文件里使用
const moodSvgIcons = import.meta.glob("@/assets/icons/moods/*.svg");
// 获取图标名称并导入
const moodIconNames = Object.keys(moodSvgIcons).map(
  (path) =>
    //path.split("/").pop()?.replace(".svg", "")
    path
);
const moodIcon = ref(null);
const weatherSvgIcons = import.meta.glob("@/assets/icons/weathers/*.svg");
// 获取图标名称并导入
const weatherIconNames = Object.keys(weatherSvgIcons).map(
  (path) =>
    //path.split("/").pop()?.replace(".svg", "")
    path
);
const weatherIcon = ref(null);
const formRef: any = ref(null);
const formValue = ref<createNotesInfoRequest & { id: string | null }>({
  id: null,
  title: null,
  weather: null,
  weatherIcon: null,
  mood: null,
  moodIcon: null,
  password: null,
  content: "",
  isRedFlag: false,
  isComments: true,
  isPrivacy: false,
  enable: true,
});
//表单初始值
const inceptionFormValue = {
  id: null,
  title: null,
  weather: null,
  weatherIcon: null,
  mood: null,
  moodIcon: null,
  password: null,
  content: "",
  isRedFlag: false,
  isComments: true,
  isPrivacy: false,
  enable: true,
};
const rules = {
  title: {
    required: true,
    trigger: ["blur", "input"],
    message: "请填写文章标题",
  },
  articleTag: {
    type: "array",
    required: true,
    trigger: ["blur", "change"],
    message: "文章还没有标签",
  },
  articleType: {
    required: true,
    trigger: ["blur", "change"],
    message: "文章还没有类型",
  },
};
const showModal = ref(false);
const myDialogRef = ref(null);
const route = useRoute();
const router = useRouter();

onMounted(() => {
  if (route.query.id) {
    getNotesById({ id: route.query.id }).then((res) => {
      formValue.value.id = res.data.id;
      formValue.value.title = res.data.title;
      formValue.value.weather = res.data.weather;
      formValue.value.weatherIcon = res.data.weatherIcon;
      formValue.value.mood = res.data.mood;
      formValue.value.moodIcon = res.data.moodIcon;
      formValue.value.password = res.data.password;
      formValue.value.content = res.data.content;
      formValue.value.isRedFlag = res.data.isRedFlag;
      formValue.value.isComments = res.data.isComments;
      formValue.value.isPrivacy = res.data.isPrivacy;
      formValue.value.enable = res.data.enable;
      weatherIcon.value = res.data.weatherIcon;
      moodIcon.value = res.data.moodIcon;
    });
  }
});

const handleValidateClick = async (e) => {
  e.preventDefault();
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      formValue.value.moodIcon = await convertSvgToBase64(moodIcon.value); // 读取文件并转为Base64
      formValue.value.weatherIcon = await convertSvgToBase64(weatherIcon.value);
      if (route.query.id) {
        updateNotes(formValue.value).then((res) => {
          if ((res.code = 200)) {
            window.$message.success(res.message);
            router.push({ path: "/notes/list" });
          } else {
            window.$message.error(res.message);
          }
        });
      } else {
        createNotes(formValue.value).then((res) => {
          if ((res.code = 200)) {
            window.$message.success(res.message);
            router.push({ path: "/notes/list" });
          } else {
            window.$message.error(res.message);
          }
        });
      }
    } else {
      console.log(formValue.value);
      window.$message.error("表单验证错误");
    }
  });
};
const closeModal = () => {
  showModal.value = false;
};
const btnView = () => {
  showModal.value = true;
  myDialogRef.value?.init(formValue.value.content, true);
};
const iconBtn = (icon, type) => {
  if (type === 1) moodIcon.value = icon;
  else if (type === 2) weatherIcon.value = icon;
};

const convertSvgToBase64 = async (svgPath) => {
  try {
    // 通过 fetch 获取 SVG 文件内容
    const response = await fetch(svgPath);

    // 获取文件的文本内容
    const svgText = await response.text();

    // 判断 SVG 内容是否存在
    if (svgText != null) {
      // 将 SVG 内容编码为 Base64
      const base64Svg = btoa(unescape(encodeURIComponent(svgText)));

      // 使用 data URL 将 SVG 内容作为图像源
      const base64SvgUrl = `data:image/svg+xml;base64,${base64Svg}`;

      // 返回转换后的 Base64 SVG 图像 URL
      return base64SvgUrl;
    }
  } catch (error) {
    console.error("Error converting SVG to Base64:", error);
    return null; // 如果发生错误，返回 null
  }
};

// async function convertSvgToBase64(svgPath) {
//   // 通过 fetch 获取 SVG 文件内容
//   await fetch(svgPath)
//     .then((response) => response.text()) // 获取文件的文本内容
//     .then((svgText) => {
//       if (svgPath != null) {
//         // 将 SVG 内容编码为 Base64
//         const base64Svg = btoa(unescape(encodeURIComponent(svgText)));

//         // 使用 data URL 将 SVG 内容作为图像源
//         const base64SvgUrl = `data:image/svg+xml;base64,${base64Svg}`;

//         // 显示转换后的 Base64 SVG 图像
//         const imgElement = document.createElement("img");
//         imgElement.src = base64SvgUrl;
//         document.body.appendChild(imgElement);
//         console.log(base64SvgUrl);
//         return base64SvgUrl;
//       }
//     })
//     .catch((error) => console.error("Error converting SVG to Base64:", error));
// }
const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
    files.map((file) => {
      return new Promise((rev, rej) => {
        const form = new FormData();
        form.append("file", file);
        console.log(form);
        uploadImageFile(form).then((res) => {
          console.log(res);
          rev(import.meta.env.VITE_APP_FILE_KEY + res.data);
        });
      });
    })
  );

  callback(res.map((item) => item));
};
</script>

<style lang="scss" scoped>
.moods {
  display: flex;
  flex-wrap: wrap;
  width: 9.1rem;
  gap: 0.2rem;
  img {
    width: 100%;
  }
}
</style>
